package com.hxy.tlias.filter;

import com.hxy.tlias.exception.BusinessException;
import com.hxy.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //1.获取url
        StringBuffer url = req.getRequestURL();
        String uri = req.getRequestURI();
        log.info("url：{}",url);
        log.info("uri：{}",uri);
        //2.判断是否包含login
        if(uri.contains("login")){
            chain.doFilter(request,response);
            //注意要结束
            return;
        }
        //3.获取请求头中的令牌
        String token = req.getHeader("token");
        //4.判断令牌是否为空
        if(token == null){
            resp.setStatus(401);
            log.error("令牌为空！！！");
            //throw new BusinessException("未登录,请先登录！");
            return;
        }
        //5.解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            resp.setStatus(401);
            log.error("令牌解析失败：{}",e.getMessage());
            //throw new RuntimeException("未登录,请先登录！");
            return;
        }
        //6.放行
        chain.doFilter(request,response);

    }
}
